#include "opencv2/opencv.hpp"

#define TARPA_FULL  0 /* 有苫布*/
#define TARPA_EMPTY 1 /* 没有苫布*/

struct TarpaResult {
    int res; /* 苫布状态，取值TARPA_XXXX */

};


float tarpaDetect(unsigned char* data, int width, int height, int* roi, int* ave)
{
    cv::Mat src(height, width, CV_8UC1, data);
    cv::Mat roiImg;
    int w,h;
    if (roi != 0) {
        roiImg = cv::Mat(src, cv::Rect(roi[0], roi[1], roi[2], roi[3])).clone();
        w = roi[2];
        h = roi[3];
    } else {
        roiImg = src.clone();
        w = width;
        h= height;
    }
    int sum = 0, divisor = 0;
    for (int i=0; i<h; i++) {
        for (int j=0; j<w; j++) {
            unsigned char value = *(roiImg.data+i*w+j);
            sum += value;
            divisor++;
            value = value >> 7;
            *(roiImg.data+i*w+j) = value*255;
        }
    }

    *ave = sum/divisor;

    cv::Mat blurImg, blurImg2, blurImg3;
	cv::medianBlur(roiImg, blurImg, 5);
	cv::medianBlur(blurImg, blurImg2, 5);
	cv::medianBlur(blurImg2, blurImg3, 5);
    int zeroItem = 0;
    for (int i=0; i<h; i++) {
        for (int j=0; j<w; j++) {
            if (*(blurImg3.data+i*w+j) == 0) zeroItem++;
        }
    }

    return zeroItem*1.0/(w*h);
}


//int main()
//{
//    printf("opencv version - %s\n", CV_VERSION);
//    getchar();
//}